import { useCallback, useEffect, useMemo, useState } from "react"
import axios from 'axios';
import qs from 'qs';

import './index.css';

export function ScanPage() {

    let [id, setId] = useState('');
    let [secret, setSecret] = useState('');
    let [base64, setBase64] = useState('');
    let [aiTextVo, setAiTextVo] = useState<AiTextVo | null>(null);
    let [token, setToken] = useState<string | null>(window.localStorage.getItem('ai_access_token'));
    const handleIdInput = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        setId(event.target.value);
    }, []);
    const handleSecretInput = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        setSecret(event.target.value);
    }, []);
    const handleTokenInput = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        setToken(event.target.value);
        window.localStorage.setItem('ai_access_token', event.target.value);
    }, []);
    const handleImgSelected = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
        if (event.target.files?.length && token) {
            const files = event.target.files;
            const base64 = await transToBase(files);
            setBase64(base64);
            const aiTextVo = await scanImg(base64, token);
            setAiTextVo(aiTextVo);
        }
    }, []);
    const clearToken = useCallback(() => {
        setToken('');
        window.localStorage.setItem('ai_access_token', '');
    }, []);
    useEffect(() => {
        if (id && secret) {
            axios.get<{access_token: string}>(`https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${id}&client_secret=${secret}`)
            .then(res => {
                const token = res.data?.access_token;
                if (!token) {
                    return;
                }
                setToken(res.data.access_token);
                window.localStorage.setItem('ai_access_token', token);
            });
        }
    }, [id, secret]);

    return <div>
        <div>
            <button onClick={clearToken}>清除缓存</button>
        </div>
        {(!id || !secret) &&
            <div>
                {/* <div>
                    <label>
                        client id
                    <input type="text" placeholder="请输入 client id" value={id} onChange={handleIdInput} />
                    </label>
                </div>
                <div>
                    <label>
                        client secret
                    <input type="text" placeholder="请输入 client secret" value={secret} onChange={handleSecretInput} />
                    </label>
                </div> */}
                <label>
                        ai_access_token
                    <input type="text" placeholder="请输入 client secret" value={token || ''} onChange={handleTokenInput} />
                    </label>
            </div>}
        {token &&
            <div>
                <input style={{ display: 'none' }} id="select-file" type="file" multiple={false} accept="image/*" onChange={handleImgSelected} />
                <div>
                    <button>
                        <label htmlFor="select-file">
                            请选择文件
                </label>
                    </button>
                </div>
                {base64 && <div><img src={base64} alt="上传的图片有点问题" /></div>}
                {aiTextVo && <div className="compare-container">
                    <img style={{ left: 0, top: 0 }} src={base64} alt="上传的图片有点问题" />
                    {compareText(aiTextVo)}
                </div>}

            </div>}
    </div>
}

function compareText(aiTextVo: AiTextVo) {
    return aiTextVo.words_result.map((item) => {
        const location = item.location;
        const style: React.CSSProperties = {
            position: 'absolute',
            top: location.top,
            left: location.left,
            fontSize: '14px',
            color: 'red'
        };
        return <div key={item.words} style={style}>{item.words}</div>
    })
}

function transToBase(files: FileList) {
    return new Promise<string>((resolve, reject) => {
        const file = files[0];
        let reader = new FileReader();
        reader.onload = (result) => {
            resolve(result.target?.result as string);
        }
        reader.readAsDataURL(file);
    })
}

function scanImg(result: string, token: string) {
    return axios.post<AiTextVo>(`https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token=${token}`,
        qs.stringify({
            image: result.replace(/data:image\/.*?;base64,/, '')
        }),
        {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(res => {
            return res.data;
        })
};

interface AiTextVo {
    log_id: number;
    words_result: {
        words: string;
        location: {
            top: number;
            left: number;
            width: number;
            height: number;
        }
    }[];
    words_result_num: number;
}